import { Component } from 'react';

import {Toast, Button , Datetime, Boxs, Context, Card, Dialog,Group} from 'saltui';
const { HBox, Box } = Boxs;
import AngleRight from 'salt-icon/lib/AngleRight';
import ShowTimeField from '../../../components/showTimeField';

import DB from '../../../app/db';
import './PageHome.less';


export default class PageHome extends Component {

 constructor(props) {
    super(props);
    let id = this.props.params.id;
    var date = this.props.params.currentDate;

    scrollTo(0, 0);
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    Dialog.hide();
    let startTime = this.getCurrentTime();
    let endTime = this.getCurrentTime();
    let currentDate = new Date(props.params.currentDate);
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let activeDate = ymdw.year + '-' + ymdw.month + '-' + ymdw.day + '(' + ymdw.week + ")";
    this.state = {
      boardroomSet: {},
      meetingServe: "",
      id: id,
      startTime: startTime,
      endTime: endTime,
      startSelect: {value: new Date(startTime).getTime()},
      endSelect: {value: new Date(endTime).getTime()},
      limitDate:'',
      selectDate: {value: new Date(date).getTime()},
      currentDate: props.params.currentDate,
      times: "",
      activeDate: activeDate,
      dateValue: currentDate.getTime(),
    };
    
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });

  }

  componentDidMount(){
    var page_title = "会议室详情";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : page_title,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: page_title,
            icon: '',
            actionmenu: {}
        },
      });
    }
    this.showBoardRoom(this.props.params.currentDate);
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  showBoardRoom(currentDate){
    var params = {
      id:this.state.id,
      date:currentDate
    }
      DB.SomeModuleAPI.boardRoomInfo(params).then((content) => {
        let server = content.server;
        var boardroomSet = content.boardroomSet.meetingServe;
        var meetingServe = "";
        if (content.server!=null && boardroomSet!=null && boardroomSet!=undefined) {
          for (var i=0; i<server.length;i++) {
            if(boardroomSet.indexOf(server[i].value) >= 0){
              meetingServe += server[i].text + ",";
            }        
          }
        }
        if(meetingServe != ""){
          meetingServe = meetingServe.substring(0,meetingServe.length-1);
        }

        var times = "";
        if(content.times != null){
          times = content.times;
        }
        this.setState({
          limitDate: content.limitDate,
          boardroomSet: content.boardroomSet,
          meetingServe: meetingServe,
          userName: content.adminUsers,
          categoryName: content.categoryName,
          times: times
        });

      }).catch((error) => {

      });
  }

  handleDateChange(value){
    var currentDate = new Date(value.value).format("yyyy-MM-dd");
    this.setState({
      selectDate: value,
      currentDate: currentDate
    });
    var params = {
      id: this.state.id,
      date: currentDate
    };
    this.showBoardRoom(currentDate);
  }

  // 新增页面
  addBpmMeeting() {
    // var canAdd = this.state.canAdd;
    // if(!canAdd){
    //   Toast.show({
    //     type: 'error',
    //     content: '请选择连续的时间段',
    //     onHide: function () {
    //     }
    //   });
    //   return false;
    // }else{
      var startTime = this.state.startTime;
      var endTime = this.state.endTime;
      var boardroomId = this.state.id;
      var isApprove = this.state.boardroomSet.isApprove;
      if(isApprove == "1"){
        var code = this.state.boardroomSet.progressId;
        var param = {code: code};
        DB.SomeModuleAPI.startProcess(param).then((content) => {
          // this.setState({
          //     flowClassifyData: content.flowClassifyData,
          //     shortcutFlowDate: content.shortcutFlowDate
          // });
          var openTaskId = content.openTaskId;
          var processInstanceId = content.processInstanceId
          var list = content.list;
          if (openTaskId != null && openTaskId != '') {
            if (list != null && list != '' && list.length > 0) {
              for (var j = 0; j < list.length; j++) {
                if (openTaskId == list[j].id) {
                  let path = 'process/processDetails/' + openTaskId + '/' + list[j].formKey + '/-1/0/0/' + processInstanceId +'/meeting?boardRoomId='+boardroomId+'&startTime='+startTime+'&endTime='+endTime;
                  location.hash = path;
                }
              }
            }
          } else {
            if(list!=null && list!='' && list.length>0){
              if(list[0]['assignee']!=null && list[0]['assignee']!=''){
                var assigneeName='';
                for(var i=0;i<list.length;i++){
                  if(list[i].assigneeName!=null && list[i].assigneeName!=''){
                    assigneeName=assigneeName+','+list[i].assigneeName;
                  }
                }
                if(assigneeName==null || assigneeName==''){
                  Toast.show({
                    type: 'error',
                    content: "请重新设置该流程的起始节点！"
                  });
                }else{
                  Toast.show({
                    type: 'success',
                    content: "流程已发送给" + assigneeName.substring(1)
                  });
                }
              }else{
                Toast.show({
                  type: 'error',
                  content: "请重新设置该流程的起始节点！"
                });
              }
            }else{
              Toast.show({
                type: 'error',
                content: "请重新设置该流程的起始节点！"
              });
            }
          }
        }).catch((error) => {
          Toast.show({
            type: 'error',
            content: "该会议室暂不支持预定"
          });
        });
      }else{
        location.hash = 'meeting/add/boardroom/undefined/'+this.state.id+'/'+startTime+'/'+endTime;
      }
    // }
  }

  showSlot(id) {
    this[id].show();
  }

  selectTimes(value){
    this.setState({
      startTime: value.startTime,
      endTime: value.endTime,
      canAdd: value.canAdd
    });
  }

  prevMonth(){
    var currentDate = new Date(this.state.currentDate);
    currentDate.setDate(currentDate.getDate() - 1);
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState ({
      currentDate: currentDate,
      activeDate: activeDate,
      dateValue: currentDate.getTime()
    },()=>{
      this.showBoardRoom(dateStr);
    });
  }

  nextMonth(){
    var currentDate = new Date(this.state.currentDate);
    currentDate.setDate(currentDate.getDate() + 1);
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState ({
      currentDate: currentDate,
      activeDate: activeDate,
      dateValue: currentDate.getTime()
    },()=>{
      this.showBoardRoom(dateStr);
    });
  }

  onConfirm(value, key){
    let date = new Date(value.value);
    let ymdw = this.getYearMonthDayWeek(date);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState({
      currentDate: date,
      dateValue: value,
      activeDate: activeDate
    },()=>{
      this.showBoardRoom(dateStr);
    });
  }

  getYearMonthDayWeek(date){
    if(date){
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var week = date.getDay();
      var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
      let data = {
        year: year,
        month: month < 10 ? '0' + month : month,
        day: day < 10 ? '0' + day : day,
        week: '星期' + weekArray[week],
      }
      return data;
    }
    return null;
  }

  getCurrentTime(){
    var date = new Date();
    var minute = date.getMinutes();
    minute = Math.ceil(minute/30)*30;
    date.setMinutes(minute);
    return date.format("yyyy-MM-dd HH:mm");
  }

  showSlot(id) {
    this[id].show();
  }

  //开始日期时间
  clickStartTime(value){
    this.setState({
      startSelect: value,
      startTime: new Date(value.value).format("yyyy-MM-dd HH:mm")
    });
  }

  //结束日期时间
  clickEndTime(value){
    this.setState({
      endSelect: value,
      endTime: new Date(value.value).format("yyyy-MM-dd HH:mm")
    });
  }

  render() {
    let t = this;
    const headerCls = Context.prefixClass('card-header');
    var boardroomSet = this.state.boardroomSet;
    var openTime = "";
    if(boardroomSet.startTime!=undefined){
      openTime = boardroomSet.startTime + "~" + boardroomSet.endTime;
    }
    var dataTimeHeader = "";
    if(this.state.startTime != undefined){
      dataTimeHeader = this.state.startTime + "~" + this.state.endTime;
    }
    var startTime = boardroomSet.startTime;
    var endTime = boardroomSet.endTime;
    if(startTime==undefined || startTime==null || startTime==""){
      startTime = "00:00";
    }
    if(endTime==undefined || endTime==null || endTime==""){
      endTime = "23:59";
    }
    
    let limitDate = t.state.limitDate ? new Date(t.state.limitDate).getTime() : new Date(2051, 0, 1).getTime() - 1;
    return (
      <div className="meeting-details t-PB68">
        <div className="card-wrap">
          <Card className="card-sence">
            <div className={headerCls + ' t-P0'}>
              <div className="card-username"> {boardroomSet.name}</div>
            </div>
              {/*<HBox>
                <Box><i className="iconfont icon-manager t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">管理员：</Box>
                <Box flex={1} className="card-desc">{this.state.userName}</Box>
              </HBox>*/}
              <HBox>
                <Box><i className="iconfont icon-user t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">坐席人数：</Box>
                <Box flex={1} className="card-desc">{"可容纳"+boardroomSet.count+"人"}</Box>
              </HBox>
              <HBox>
                <Box><i className="iconfont icon-time t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">开放时段：</Box>
                <Box flex={1} className="card-desc">{boardroomSet.startTime}~{boardroomSet.endTime}</Box>
              </HBox>
              <HBox>
                <Box><i className="iconfont icon-place t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">地址：</Box>
                <Box flex={1} className="card-desc">{boardroomSet.address}</Box>
              </HBox>
              <HBox>
                <Box><i className="iconfont icon-service t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">会议服务：</Box>
                <Box flex={1} className="card-desc">{this.state.meetingServe}</Box>
              </HBox>
              <HBox>
                <Box><i className="iconfont icon-type t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">类型：</Box>
                <Box flex={1} className="card-desc">{this.state.categoryName}</Box>
              </HBox>
              <HBox>
                <Box><i className="iconfont icon-discribe t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                <Box className="card-desc">描述：</Box>
                <Box flex={1} className="card-desc">{this.state.boardroomSet.description}</Box>
              </HBox>
          </Card>
          {/* <div className="t-BCe t-FS16 t-LH2 t-P8">选择预约时段</div> 
          <Group.List>
            <HBox className="t-field-box t-FBAC">
              <div className="t-FS16" required >时段：<span>{ dataTimeHeader }</span></div>
              <HBox flex="1" className="t-FBAC">
                <Box flex="1"><span className="t-FR t-FS16">{this.state.currentDate}</span></Box>
                <Box className="t-FBAC t-field-icon">
                  <i className="iconfont icon-calendar1 t-FCc t-MR4" style={{fontSize:16}}></i>
                </Box>
              </HBox>          
            </HBox>
          </Group.List>
          <CheckTimeField startTime={ startTime } 
            endTime={ endTime } selectDate={this.state.currentDate} times={this.state.times} onSelected={(value) => this.selectTimes(value)}></CheckTimeField>
            */}
           {/* 日期选择部分 */}
           <div className="t-BCf7 t-H10"></div>
           <div className="dd-bottom-border t-BCf calendar-choose">
            <HBox vAlign="center" className="dd-t-room-date">
                <Box className="t-FCddblue" onClick={this.prevMonth.bind(this)}>前一天</Box>
                <Box className="data-btn t-FAC t-PT2" onClick={()=> {t.dateSlot.show()}}>
                  {t.state.activeDate}
                  {/*<i className="iconfont icon-calendar-set t-ML6" style={{ fontSize: 16 }}></i>*/}
                </Box>
                <Box className="t-FCddblue" onClick={this.nextMonth.bind(this)}>后一天</Box>
                <Datetime 
                  slotRef={s => t.dateSlot = s}
                  title="时间选择"
                  value={t.state.dateValue}
                  columns={Datetime.YMD}
                  onConfirm={(value) => { this.onConfirm(value, 'dateValue'); }}
                />
              </HBox>
              {/* 滑块显示 */}
              <ShowTimeField 
                startTime={ startTime } 
                endTime={ endTime }
                times={this.state.times}
                />
            </div>

            {/* 选择预定时间段 */}
            <div>
              <Box className="t-P16 t-FS16">选择预定时段</Box>
              <Group.List>
                <HBox className="t-field-box t-FBAC">
                  <div className="t-field-layout-h-label t-FS16 required" >开始时间</div>
                  <HBox flex="1" onClick={() => {t.showSlot('startSlot')}} className="t-FBAC">
                    <Box flex="1"><span className="t-FL t-FS16">{t.state.startTime}</span></Box>
                      <Box className="t-FBAC t-field-icon">
                        <AngleRight width={20} fill="#ccc"/>
                        <Datetime
                          locale="zh-cn"
                          minuteStep={5}
                          slotRef={(s) => t.startSlot = s}
                          title="日期选择"
                          value={t.state.startSelect}
                          columns={Datetime.YMDHM}
                          maxDate={limitDate}
                          onConfirm={(value) => { this.clickStartTime(value); }}
                        />
                      </Box>
                  </HBox>
                </HBox>
            </Group.List>
            <Group.List>
                <HBox className="t-field-box t-FBAC">
                  <div className="t-field-layout-h-label t-FS16 required" >结束时间</div>
                  <HBox flex="1" onClick={() => {t.showSlot('endSlot')}} className="t-FBAC">
                    <Box flex="1"><span className="t-FL t-FS16">{t.state.endTime}</span></Box>
                      <Box className="t-FBAC t-field-icon">
                        <AngleRight  width={20}  fill="#ccc"/>
                        <Datetime
                          locale="zh-cn"
                          minuteStep={5}
                          slotRef={(s) => t.endSlot = s}
                          title="日期选择"
                          value={t.state.endSelect}
                          columns={Datetime.YMDHM}
                          maxDate={limitDate}
                          onConfirm={(value) => { this.clickEndTime(value); }}
                        />
                      </Box>
                  </HBox>
                </HBox>
            </Group.List>
            </div>
        </div> 
        <div>
          <Button.Group>
            <Button type="primary" display="inline" onClick={this.addBpmMeeting.bind(this)}>预定会议室</Button>
          </Button.Group>
        </div>   
        </div>)
  }
}


